package com.wunu.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.wunu.service.IMenuService;
import com.wunu.service.IRoleToMenuService;
import com.wunu.entity.Menu;
import com.wunu.entity.RoleToMenu;
import com.wunu.mapper.RoleToMenuMapper;
import com.wunu.model.RoleToMenuModel;
import com.wunu.util.ComUtil;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wunu kin
 * @since 2019-03-25
 */
@Service
public class RoleToMenuServiceImpl extends ServiceImpl<RoleToMenuMapper, RoleToMenu> implements IRoleToMenuService {
    @Autowired
    private RoleToMenuMapper mapper;
    @Autowired
    private IMenuService menuService;
     /**
            * 获取菜单权限列表
      * @param roleMenuPage
      * @param roleCode
      * @return
      */
	 public Page<RoleToMenuModel> selectPermissionPage(Page<RoleToMenuModel> roleMenuPage, String roleCode) {
		 if(StringUtils.isEmpty(roleCode)) {
			 return roleMenuPage.setRecords(mapper.selectPermissionPage(roleMenuPage));
		 }
		 return roleMenuPage.setRecords(mapper.selectByRoleCodePage(roleMenuPage, roleCode));
	 }
	 
	 
    @Override
    //redis生成key注解，以类名方法名和参数组成key
    //@Cacheable(value = "UserToRole",keyGenerator="wiselyKeyGenerator")
    public List<RoleToMenu> selectByRoleCode(String roleCode) {
        EntityWrapper<RoleToMenu> ew = new EntityWrapper<>();
        ew.where("roleCode={0}", roleCode);
        return this.selectList(ew);
    }

    @Override
    public boolean saveAll(List<RoleToMenu> menuCodes) {
        boolean result = true;
   
        if (!ComUtil.isEmpty(menuCodes)) {
            List<Menu> mList = menuService.selectByParentIdList(0);
            List<RoleToMenu> modelList = new ArrayList<>();
            for (RoleToMenu roleMenu : menuCodes) {
            	for (Menu menu : mList) {
					if(menu.getMenuId()==roleMenu.getParentId()) {
						modelList.add(RoleToMenu.builder().roleCode(roleMenu.getRoleCode()).menuCode(menu.getMenuCode()).build());
					}
				}
                modelList.add(RoleToMenu.builder().roleCode(roleMenu.getRoleCode()).menuCode(roleMenu.getMenuCode()).rights(roleMenu.getRights()).build());
            }
            result = this.insertBatch(modelList);
        }
        return result;
    }

    @Override
    public boolean deleteAllByRoleCode(String roleCode) {
        EntityWrapper<RoleToMenu> ew = new EntityWrapper<>();
        ew.where("roleCode={0}", roleCode);
        return this.delete(ew);
    }


	@Override
	public RoleToMenuModel findPermissionByCode(String roleCode,String menuCode) throws Exception {
		RoleToMenuModel permissionMap =  mapper.findPermissionByCode(menuCode, roleCode);
		return permissionMap;
	}
}
